package com.tianxiabuyi.weixin.qy;

import com.tianxiabuyi.weixin.common.AccessTokenHolder;
import com.tianxiabuyi.weixin.common.DefaultAccessTokenHolder;
import com.tianxiabuyi.weixin.common.WxClient;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信企业号客户端工厂
 */
public class QyWxClientFactory {

    private static QyWxClientFactory instance = null;
    private static ConcurrentHashMap<String, WxClient> wxClients = new ConcurrentHashMap<>();

    private QyWxClientFactory(){
    }

    public synchronized static QyWxClientFactory getInstance() {
        if (instance == null) {
            instance = new QyWxClientFactory();
        }
        return instance;
    }

    /**
     *  初始化wxclient
     * @param corpId
     * @param corpSecret
     * @return
     */
    public WxClient with(String corpId, String corpSecret) {
        if (!wxClients.containsKey(key(corpId, corpSecret)) ) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
            AccessTokenHolder accessTokenHolder =  new DefaultAccessTokenHolder(url, corpId, corpSecret);
            WxClient wxClient = new WxClient(corpId, corpSecret, accessTokenHolder);
            wxClients.putIfAbsent(key(corpId, corpSecret), wxClient);
        }
        return wxClients.get(key(corpId, corpSecret));
    }

    private String key(String corpId,  String corpSecret) {
        return corpId+ ":" + corpSecret;
    }
    //{"corpid":"wx997ea53e3821a059","secret":"5ZhlQckJGhoQqV4Dg6wKprozVwOQ8AE5-R41DgLuAu15YarOPU7cOdvv0N4TtDM0","redirect_uri":""}
    public static void main(String[] args) {
        WxClient wx = QyWxClientFactory.getInstance().with("wx997ea53e3821a059", "5ZhlQckJGhoQqV4Dg6wKprozVwOQ8AE5-R41DgLuAu15YarOPU7cOdvv0N4TtDM0");
        String accessToken = wx.getAccessToken().getAccessToken();
        System.out.println(accessToken);
    }

}

